<template>
	<div class="system-dept-container">
		<el-card shadow="hover">
			<div class="system-dept-search mb15">
        <el-form :inline="true">
			<el-form-item label="订单号">
				<el-input size="default" v-model="tableData.param.order_num" placeholder="请输入名称" class="w-50 m-2" clearable/>
			  </el-form-item>
          <el-form-item label="名称">
            <el-input size="default" v-model="tableData.param.name" placeholder="请输入名称" class="w-50 m-2" clearable/>
          </el-form-item>
		  <el-form-item label="状态">
            <el-select size="default" placeholder="请选择状态" class="w-50 m-2" v-model="tableData.param.status" clearable>
              <el-option label="正常"  value="1" />
			  <el-option label="完成"  value="2" />
              <el-option label="关闭"  value="0" />
            </el-select>
          </el-form-item>
		  <el-form-item label="是否外出单">
            <el-select size="default" placeholder="请选择" class="w-50 m-2" v-model="tableData.param.is_out" clearable>
              <el-option label="是"  value="1" />
              <el-option label="否"  value="0" />
            </el-select>
          </el-form-item>
		  <el-form-item label="是否预约单">
            <el-select size="default" placeholder="请选择" class="w-50 m-2" v-model="tableData.param.is_appointment" clearable>
              <el-option label="是"  value="1" />
              <el-option label="否"  value="0" />
            </el-select>
          </el-form-item>
		  <el-form-item label="所属店铺">
			<el-cascader
				:options="shop_list"
				:props="{ emitPath:false, value: 'id', label: 'name',expandTrigger: 'hover' as const, }"
				placeholder="请选择店铺"
				clearable
				class="w100"
				:show-all-levels="false"
				v-model="tableData.param.shop_id">
			</el-cascader>
		  </el-form-item>
		  <el-form-item label="会员">
			<el-select
			  v-model="m_value"
			  value-key="id"
			  filterable
			  remote
			  clearable
			  reserve-keyword
			  placeholder="请输入会员姓名或联系方式"
			  :remote-method="memberSearch"
			  :loading="m_loading"

			  >
			<el-option
			  v-for="item in m_option"
			  :key="item.id"
			  :label="item.name"
			  :value="item"
			/>
		  </el-select>
		  </el-form-item>
		  <el-form-item label="员工">
							
			<el-select
			  v-model="e_value"
			  filterable
			  remote
			  clearable
			  reserve-keyword
			  placeholder="请输入员工姓名或联系方式"
			  :remote-method="employeeSearch"
			  :loading="e_loading"
			  value-key="id"
			  @change="employeeChange"
			  >
			<el-option
			  v-for="item in e_option"
			  :key="item.id"
			  :label="item.name"
			  :value="item"
			/>
		  </el-select>
		  </el-form-item>

		  <el-form-item label="订单开始时间">
			<el-date-picker
			v-model="time_value"
			type="datetimerange"
			range-separator="至"
			start-placeholder="开始时间"
			end-placeholder="结束时间"
			value-format="YYYY-MM-DD HH:mm:ss"
		  />
 </el-form-item>
				  <el-form-item>
            <el-button size="default" type="primary" class="ml10" @click="initList">
              <el-icon>
                <ele-Search />
              </el-icon>
              查询
            </el-button>
            <el-button size="default" type="success" class="ml10" @click="onOpenAdd">
              <el-icon>
                <ele-FolderAdd />
              </el-icon>
              新增
            </el-button>
			<el-button size="default" type="warning" class="ml10" @click="exportExcel">
				<el-icon>
				  <ele-FolderAdd />
				</el-icon>
				导出
			  </el-button>
          </el-form-item>
        </el-form>
      </div>
			<el-table
				:data="tableData.data"
				style="width: 100%"
				row-key="id" 
			>
			<el-table-column prop="order_num" label="订单号" show-overflow-tooltip width="200px"> </el-table-column>
			<el-table-column prop="shop_info.name" label="所属店铺" show-overflow-tooltip width="200px"> </el-table-column>
				<el-table-column prop="name" label="名称" show-overflow-tooltip> </el-table-column>
				<el-table-column prop="contact" label="联系方式" show-overflow-tooltip> </el-table-column>
				<el-table-column prop="status" label="状态" show-overflow-tooltip width="100px">
					<template #default="scope">
						<el-tag type="primary" v-if="scope.row.status===1">正常</el-tag>
						<el-tag type="success" v-else-if="scope.row.status===2">完成</el-tag>
						<el-tag type="info" v-else>关闭</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="money" label="金额" show-overflow-tooltip> </el-table-column>
				<el-table-column prop="start_time" label="开始时间" show-overflow-tooltip> </el-table-column>
				<el-table-column prop="end_time" label="结束时间" show-overflow-tooltip> </el-table-column>

				<el-table-column prop="status" label="类型" show-overflow-tooltip width="100px">
					<template #default="scope">
						<el-tag type="primary" v-if="scope.row.type===1">个人</el-tag>
						<el-tag type="primary" v-else-if="scope.row.type===2">团体</el-tag>
						<el-tag type="primary" v-else>其它</el-tag>
					</template>
				</el-table-column>
			<el-table-column label="化妆师" show-overflow-tooltip> 
				<template #default="scope">
					{{ scope.row.employee_infos?scope.row.employee_infos.map((v:any)=>{return v.name;}).join(","):'' }}
				</template>
			</el-table-column>
			<el-table-column label="客服员工" show-overflow-tooltip> 
				<template #default="scope">
					{{ scope.row.customer_service_employee?scope.row.customer_service_employee.name:'' }}
				</template>
			</el-table-column>

				<el-table-column label="是否会员" show-overflow-tooltip> 
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.member_id>0">是</el-tag>
						<el-tag type="info" v-else>否</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="是否外出单" show-overflow-tooltip> 
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.is_out>0">是</el-tag>
						<el-tag type="info" v-else>否</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="是否预约单" show-overflow-tooltip> 
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.is_appointment>0">是</el-tag>
						<el-tag type="info" v-else>否</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" show-overflow-tooltip> </el-table-column>

				
				<el-table-column label="操作" width="100" fixed="right">
					<template #default="scope">

						<el-button size="small" text type="primary" @click="onOpenEdit(scope.row)">修改</el-button>
						<el-button size="small" text type="primary" @click="onTabelRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<pagination
          v-show="tableData.total>0"
          :total="tableData.total"
          v-model:page="tableData.param.pageNum"
          v-model:limit="tableData.param.pageSize"
          @pagination="initList"
      />
		<Edit ref="editRef" @list="initList"/>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, defineComponent,getCurrentInstance } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import Edit from '/@/views/zmm/order/component/edit.vue';
import {destory, getList} from "/@/api/zmm/order";
import {getList as shopGetList} from "/@/api/zmm/shop";
import {getMemberOpQueryList} from "/@/api/zmm/member";
import {getOpQueryList} from "/@/api/zmm/employee";


import * as XLSX from 'xlsx';
import { formatDate } from '/@/utils/formatTime';

// 定义接口来定义对象的类型
interface TableDataRow {
  id:number;
  name: string;
	contact: string;
	remark: string;
	status: number;
}
interface TableDataState {
	tableData: {
		data: Array<TableDataRow>;
		loading: boolean;
		total: number;

		param: {
			pageNum: number;
			pageSize: number;
			name:string;
			status:string;
			order_num:string;
			shop_id:string;
			is_out:string;
			is_appointment:string;
			end_time:string;
			start_time:string;
			member_id:string;
			employee_id:string;

		};
	};
	m_option:SOption[];
	m_value:SOption;
	m_loading:boolean;
	e_option:SOption[];
	e_value:SOption;
	e_loading:boolean;
	shop_list:Array<any>;
}
interface SOption  {
  id: number
  name: string
  contact: string
}

export default defineComponent({
	name: 'zmm_order',
	components: { Edit },
	setup() {
		let time_value = ref('')
		const times = ['00:00:00', '23:59:59']

		const memberSearch = (query: string)=>{
			if(query){
				state.m_loading = true
				getMemberOpQueryList({
					op_query:query,
				}).then((res)=>{
					state.m_loading = false
					state.m_option = res.data.list
					// console.log(state.m_option)
				})
			}
		};
		const employeeSearch = (query: string)=>{
			if(query){
				state.e_loading = true
				getOpQueryList({
					op_query:query,
				}).then((res)=>{
					state.e_loading = false
					state.e_option = res.data.list
				})
			}
		};
		const exportExcel = ()=>{
			const columns:object = {
				'order_num':'订单编号',
				'shop_name':'所属店铺',
				'name':'客户名称',
				'contact':'客户联系方式',
				'address':'工作地址',
				'start_time':'开始时间',
				'end_time':'完成时间',
				'type':'类型',
				'status':'状态',
				'is_out':'是否外出单',
				'is_appointment':'是否预约单',
				'is_member':'是否会员',
				'money':'金额',
				'employees':'化妆师',
				'customer_service_employee':'客服员工',
				'remark':'备注',
			};
			if(time_value && time_value.value){
			state.tableData.param.start_time = time_value.value[0];
			state.tableData.param.end_time = time_value.value[1];
		}else{
			state.tableData.param.start_time = '';
			state.tableData.param.end_time = '';
		}
		if(state.m_value.id > 0){
			state.tableData.param.member_id = state.m_value.id.toString()
		}else{
			state.tableData.param.member_id = '';
		}
		if(state.e_value.id > 0){
			state.tableData.param.employee_id = state.e_value.id.toString()
		}else{
			state.tableData.param.employee_id = '';
		}
		
			state.tableData.param.pageNum = -1;
			state.tableData.param.pageSize = -1;
			let list:any[] = []
			getList(state.tableData.param).then((res:any)=>{
				list = res.data.list;



				let data:any[] = [[],]
				for (let key in columns) {
					if (columns.hasOwnProperty(key)) {
						// console.log(columns[key])
						data[0].push(columns[key])
					}
				}
			
				for(let i in list){
					let d:any[] = []
					list[i]['type'] = list[i]['type'] == 1 ? '个人' : list[i]['type'] == 2 ? '团体' :  '其它';
					list[i]['status'] = list[i]['status'] == 1 ? '正常' : list[i]['status'] == 2 ? '完成' :  '废弃';
					list[i]['is_out'] = list[i]['is_out'] == 1 ? '是' : '否';
					list[i]['is_appointment'] = list[i]['is_appointment'] == 1 ? '是' : '否';
					list[i]['is_member'] = list[i]['member_id'] > 0 ? '是' : '否';
					list[i]['employees'] = list[i]['employee_infos'] ? list[i]['employee_infos'].map((v:any)=>{return v.name;}).join(","):'';
					list[i]['shop_name'] = list[i]['shop_info'] ? list[i]['shop_info']['name']:'';
					list[i]['customer_service_employee'] = list[i]['customer_service_employee'] ? list[i]['customer_service_employee']['name']:'';

					for (let key in columns) {
						if (columns.hasOwnProperty(key)) {
							
							if(list[i][key]){
								d.push(list[i][key])
							}else{
								d.push('')
							}
							
						}
					}
					data.push(d)
				}
				
				// console.log(data)

				const ws = XLSX.utils.aoa_to_sheet(data);
				const wb = XLSX.utils.book_new();
				XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
				XLSX.writeFile(wb, '订单导出'+formatDate(new Date,"YYYYmmddHHMMSS")+'.xlsx');
			
			});
			
				

			


		};
    const {proxy} = getCurrentInstance() as any;
		const editRef = ref();
		const state = reactive<TableDataState>({
			tableData: {
				data: [],
				loading: false,
				total: 0,
				param: {
					pageNum: 1,
					pageSize: 10,
					name:'',
					status: '',
					order_num: '',
					shop_id:'',
			is_out:'',
			is_appointment:'',
			start_time:'',
			end_time:'',
			member_id:'',
			employee_id:'',
				},
			},
			shop_list:[],
			m_option:[],
			m_value:{id:0,name:'',contact:''},
				m_loading:false,
				e_option:[],
			e_value:{id:0,name:'',contact:''},
				e_loading:false,
		});
		// 初始化表格数据
		const initTableData = () => {
			initList();
			shopGetList().then((res:any)=>{
		state.shop_list = proxy.handleTree(res.data.zmm_shop_list??[], "id","up_id");

      });
		};
    const initList = ()=>{
		if(time_value && time_value.value){
			state.tableData.param.start_time = time_value.value[0];
			state.tableData.param.end_time = time_value.value[1];
		}else{
			state.tableData.param.start_time = '';
			state.tableData.param.end_time = '';
		}
		if(state.m_value.id > 0){
			state.tableData.param.member_id = state.m_value.id.toString()
		}else{
			state.tableData.param.member_id = '';
		}
		if(state.e_value.id > 0){
			state.tableData.param.employee_id = state.e_value.id.toString()
		}else{
			state.tableData.param.employee_id = '';
		}

      getList(state.tableData.param).then((res:any)=>{
        state.tableData.data = res.data.list;
		state.tableData.total = res.data.total;
      });
    };
		// 打开新增菜单弹窗
		const onOpenAdd = (row?: TableDataRow) => {
      editRef.value.openDialog(row?.id);
		};
		// 打开编辑菜单弹窗
		const onOpenEdit = (row: TableDataRow) => {
			editRef.value.openDialog({...row});
		};
		// 删除当前行
		const onTabelRowDel = (row: TableDataRow) => {
			ElMessageBox.confirm(`此操作将永久删除：${row.name}, 是否继续?`, '提示', {
				confirmButtonText: '删除',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
          destory(row.id).then(()=>{
					  ElMessage.success('删除成功');
            initList();
          })
				})
				.catch(() => {});
		};
		// 页面加载时
		onMounted(() => {
			initTableData();
		});
		return {
			editRef,
      initList,
			onOpenAdd,
			onOpenEdit,
			onTabelRowDel,
			exportExcel,
			...toRefs(state),
			time_value,
			times,
			memberSearch,
			employeeSearch,
		};
	},
});
</script>
